package com.aote.util;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.browsesoft.dbtools.DBTools;

/**
 * 成批执行SQL的基础，语句在xml元素上配置
 */
public abstract class BatchSQLQueryBase {
	/**
	 * 对应的配置
	 */
	private Element config;

	public void setConfig(Element config) {
		this.config = config;
	}

	/**
	 * sql查询
	 */
	public List getDatas() {
		List result = new LinkedList();
		Element sqlsElem = (Element) config.getElementsByTagName("datasqls")
				.item(0);
		NodeList uniteSqls = sqlsElem.getElementsByTagName("unite");
		for (int i = 0; i < uniteSqls.getLength(); i++) {
			Element uniteElem = (Element) uniteSqls.item(i);
			// 得到配置的一批sql
			List sqls = getUniteSqls(uniteElem);
			// 得到sql的关键字的个数
			String sNum = uniteElem.getAttribute("keynumber");
			int num = Integer.parseInt(sNum);
			String[][] tempData = executeUniteSqls(sqls, num);
			result.addAll(arrayToHashtable(tempData));
		}
		return result;
	}

	/**
	 * 得到单个unite配置元素中配置的sql
	 */
	private List getUniteSqls(Element unite) {
		List result = new LinkedList();
		NodeList list = unite.getElementsByTagName("sql");
		for (int i = 0; i < list.getLength(); i++) {
			Element sqlElement = (Element) list.item(i);
			String value = sqlElement.getAttribute("value");
			result.add(value);
		}
		return result;
	}

	/**
	 * 执行一批sql并将数据最后列合并
	 * 
	 * @param n
	 *            关键字的个数，根据关键字合并
	 */
	private String[][] executeUniteSqls(List sqls, int num) {
		try {
			String[][] datas = null;
			Iterator iter = sqls.iterator();
			while (iter.hasNext()) {
				String sql = (String) iter.next();
				// 替换sql中的参数
				sql = this.replaceParams(sql);
				Logger.getLogger(this.getClass()).info(sql);
				String[][] tempDatas = DBTools.executeQueryWithTableHead(sql);
				if (datas == null) {
					datas = tempDatas;
				} else {
					// 合并，将tempdatas的最后一列（即数据列，合并到datas中）
					datas = ArrayHelper.uniteLastCols(datas, tempDatas, num);
				}
			}
			return datas;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 将数组转为hashtable
	 */
	private List arrayToHashtable(String[][] arrayData) {
		try {
			List result = new LinkedList();
			for (int i = 1; i < arrayData.length; i++) {
				Hashtable ht = DBTools.getAttributes(arrayData, i);
				result.add(ht);
			}
			return result;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 替换sql中的参数为父组件模型的属性值
	 */
	protected abstract String replaceParams(String sql);
}
